import TencentCloudChat from '@tencentcloud/chat';
import TIMUploadPlugin from 'tim-upload-plugin';
// #ifdef APP-PLUS || H5
import {NativeObject} from '@/static/native-msg/index.js'
// #endif
// APP ID
const SDKAppID= 1600076403;
//日志级别
const LogLevel=1;

//console.log(NativeObject);
//对像 
const TencentIM={
	object:null,
	isListening :null,// 是否已注册监听事件
	isReady:false, // 监听是否就绪
	NotReadyRestarTimer:null, // 断开时重启登录定时器
	promiseRestarTimer:null, // 腾讯IM登录错误重户登录定时器
	instance:()=>{
		if(TencentIM.object == null){
			//console.log('初始化...');
			// 创建 SDK 实例，
			let options={
				   SDKAppID:SDKAppID
				};
			TencentIM.object=TencentCloudChat.create(options);
			// 设置 SDK 日志输出级别，开发为 0 ，生产环境 1 
			TencentIM.object.setLogLevel(LogLevel);
			// 注册腾讯云即时通信 IM 上传插件，即时通信 IM SDK 发送图片、语音、视频、文件等消息需要使用上传插件，将文件上传到腾讯云对象存储
			TencentIM.object.registerPlugin({'tim-upload-plugin': TIMUploadPlugin});
		}
		return TencentIM.object;
	},
	login:async(type=0,toId='',msg='',successBack='',failBack='')=>{
		
		let localUserSig=uni.$utils.getCache('tencentimsig',(3600*2)-10);
		if(!localUserSig){
			let ret=await uni.$get('/appapi-config-getusersig');
			if(ret.error_code == 454555){ //已在其它设置登录
			    clearInterval(TencentIM.NotReadyRestarTimer);
				clearTimeout(TencentIM.promiseRestarTimer);
				uni.$unsetToken();
				try{TencentIM.logout();}catch (err) {}
				uni.$utils.showModal('帐号已在另一台设备登录',0,()=>{
					uni.$utils.goPage('/pages/login-app/login-app',2);
				});
				return;
			}else if(ret.error_code != 0){ //未登录
			    clearInterval(TencentIM.NotReadyRestarTimer);
				clearTimeout(TencentIM.promiseRestarTimer);
				uni.$unsetToken();
				try{TencentIM.logout();}catch (err) {}
				uni.$utils.goPage('/pages/login-app/login-app',2);
				return;
			}
			localUserSig=ret.data;
			uni.$utils.setCache('tencentimsig',localUserSig);
		}else{
			let ret=await uni.$get('/appapi-config-islogin');
			if(ret.error_code != 0){
				uni.$utils.setCache('tencentimsig',null);
				uni.$unsetToken();
				try{TencentIM.logout();}catch (err) {}
				uni.$utils.goPage('/pages/login-app/login-app',2);
			}
		}
        //TencentIM.logout();
		let user_id=localUserSig.user_id;
		uni.$vuex.state.globalData.user=localUserSig;
		user_id=user_id.toString();
		let userSig=localUserSig.userSig;
		let promise =TencentIM.instance().login({userID: user_id, userSig: userSig});
		promise.then(function(imResponse) {
		  /*console.log(imResponse.data); // 登录成功据
		  if (imResponse.data.repeatLogin === true) {
		    // 标识账号已登录，本次登录操作为重复登录。
		    console.log(imResponse.data.errorInfo);
		  }*/
		  //console.log('login:async','IM登录成功');
		  //登录成功取消定时器
		  clearInterval(TencentIM.NotReadyRestarTimer);
		  if(toId && msg) TencentIM.createTextMessage(type,toId,msg,successBack);
		}).catch(function(imError) {
		  //console.warn('login error:', imError); // 登录失败的相关信息
		  clearInterval(TencentIM.NotReadyRestarTimer);
		  clearTimeout(TencentIM.promiseRestarTimer);
		  TencentIM.promiseRestarTimer = setTimeout(()=>{
		  	TencentIM.login();
		  },30000);
		});
	},
	
	// 断开自动登录 
	onSdkNotReady:(event)=>{
		/*uni.$utils.showToast('[-100002]服器内部错误');
		TencentIM.instance().isReady=false;
		TencentIM.instance().NotReadyRestarTimer = setInterval(()=>{
			TencentIM.login();
		},10000);
		console.log('onSdkNotReady',event);*/
	},
	
	//监听已就绪
	noSdkIsReady:(event)=>{
		let isReady = TencentIM.instance().isReady();
		TencentIM.instance().isReady=isReady;
		uni.$vuex.state.globalData.imLoginStatus=true;
		console.log('noSdkIsReady',event);
		// 立即收到的离线消息
		if(!event.data){
			
		}
	},
	
	//收到会话列表通知
	conversation:(event)=>{
		// 收到会话列表更新通知，可通过遍历 event.data 获取会话列表数据并渲染到页面
		 // event.name - TencentCloudChat.EVENT.CONVERSATION_LIST_UPDATED
		 // event.data - 存储 Conversation 对象的数组 - [Conversation]
		// console.log('conversation',event.data);
		//uni.$vuex.state.globalData.isSyncCompleted=false;
		 TencentIM.getConversationList();
		 TencentIM.getGroupApplicationListCount();// 获取入群申请数量
	},
	
	//会话ID是否免打扰
	isNotDisturb:(conversationID)=>{
		let list=uni.$vuex.state.globalData.conversationList;
		//console.log('isNotDisturb',list);
		for(let i in list){
			if(list[i].conversationID == conversationID){
				if(list[i].messageRemindType != 'AcceptAndNotify'){
					return true;
				}
			}
		}
		return false;
	},
	
	//监听接收消息	
	// Message 数据结构详情请参考 https://web.sdk.qcloud.com/im/doc/v3/zh-cn/Message.html
	messageReceived:(event)=>{
		// 收到推送的单聊、群聊、群提示、群系统通知的新消息，可通过遍历 event.data 获取消息列表数据并渲染到页面
		// event.name - TencentCloudChat.EVENT.MESSAGE_RECEIVED
		// event.data - 存储 Message 对象的数组 - [Message]
		//console.log('messageReceived',event.data[0]);
		if(!event.data) return;
		let icon='';
		let path='';
		let warningTypeStr='';
		let description='';
		let to='';
		//过滤
		let makr=uni.$appConfig.IM_PREFIX_MAKR;
		let repString='';
		let unreadCount='';
		let emojiString='';
		for(let i in event.data){
			//console.log('event.data.'+i,event.data[i].nick);//每条数据
			if(event.data[i].type == 'TIMGroupSystemNoticeElem') {
				TencentIM.getGroupApplicationListCount(); //暂时不处理系统通知，以后再算
				continue; 
			} 
			//console.log('event.data[i]',event.data[i]);
			//在当前聊天界面追加数据
			if(uni.$vuex.state.globalData.currentConversId == event.data[i].conversationID){
				event.data[i]=TencentIM.messageCustom(event.data[i]);
				uni.$vuex.state.globalData.messageList.unshift(event.data[i]); // 追加消息显示
				TencentIM.setMessageRead(event.data[i].conversationID);
				//显示底部有新消息
				if(uni.$vuex.state.globalData.scrollTopValue > 0){
					uni.$vuex.state.globalData.showToBottom=true;
				}
			}
			//不在聊天界面的给提示
			if(uni.$vuex.state.globalData.currentConversId != event.data[i].conversationID){
				if(TencentIM.isNotDisturb(event.data[i].conversationID)) return; //免打扰不弹通知
				//console.log('messageReceived',event.data[i]);
				//播放消息提示
				//uni.$utils.infoRemind();
				 // #ifdef APP-PLUS || H5 
				 let nitivInfo='';
				 //过滤
				 for(let j in makr){
					 if(event.data[i].payload.text){
						 repString=event.data[i].payload.text;
						 if(repString.indexOf(makr[j].rule) > -1){
							 if(j == 'da_zhao_hu'){
								 nitivInfo='[打招呼]'+repString;
							 }else if(j == 'fa_hong_bao'){
								 nitivInfo='[红包]';
							 }else if(j == 'shou_hong_bao'){
								 nitivInfo='[已收红包]';
							 }else if(j == 'fa_tu_pian'){
								 nitivInfo='[图片]';
							 }else if(j == 'fa_shi_pin'){
								 nitivInfo='[视频]';
							 }
						 }
					 }
				 }
				 
				//单聊
				if(event.data[i].conversationType == 'C2C'){
					icon=event.data[i].avatar;
					warningTypeStr=event.data[i].nick;
					to=event.data[i].from;
					path='/pages/chat-single/chat-single?conversationID='+event.data[i].conversationID+'&nick='+warningTypeStr+'&to='+to;
					description=nitivInfo ? nitivInfo : event.data[i].payload.text
				}else{ // 群聊
					icon=event.data[i].avatar;
					warningTypeStr=event.data[i].nick;
					to=event.data[i].to;
					path='/pages/chat-group/chat-group?conversationID='+event.data[i].conversationID+'&nick='+warningTypeStr+'&to='+to;
					description='[群消息]'+(nitivInfo ? nitivInfo : event.data[i].payload.text)
				}
				
				if(event.data[i].type == 'TIMSoundElem'){
					description='[语音消息]';
				}else{
					description= TencentIM.noticeFilter(event.data[i].type,description);
				}
				if(event.data[i].type != 'TIMGroupTipElem'){ //加入群聊不弹出通知，以后再算
					NativeObject().create({
						icon:icon,   // 显示图标
						path:path, // 需要跳转路径
						warningTypeStr: warningTypeStr,  // 消息标题
						projectName: "现在",    // 时间
						description: description //通知内容
					},(res)=>{
						// 获取页面栈
						const pages = getCurrentPages();
						if (pages.length === 0) return;
						const currentPage = pages[pages.length - 1];
						if((currentPage.route).indexOf('chat-single/chat-single') >-1 || (currentPage.route).indexOf('chat-group/chat-group') >-1){
							uni.redirectTo({url:res.result.path});
						}else{
							uni.navigateTo({url:res.result.path});
						}
					});
				}
				// #endif
			}
		}
	},
	
	//获取会话列表
	getConversationList:()=>{
	    if(!uni.$vuex.state.globalData.imLoginStatus) return;
		// 获取全量的会话列表
		let promise = TencentIM.instance().getConversationList();
		promise.then(function(imResponse) {
		  const list = imResponse.data.conversationList; // 全量的会话列表，用该列表覆盖原有的会话列表
		  const isSyncCompleted = imResponse.data.isSyncCompleted; // 从云端同步会话列表是否完成
		  //系统通知不处理
		  let conversationList=[];
		  let j=0;
		  for(let c in list){
			  if(list[c].type != '@TIM#SYSTEM') conversationList[j++]=list[c];
		  }
		  let sum=0;
		  let makr=uni.$appConfig.IM_PREFIX_MAKR;
		  let repString='';
		  let unreadCount='';
		  let emojiString='';
		  for(let i in conversationList){
			  if(conversationList[i].type == 'GROUP') conversationList[i].avatars=uni.$utils.getProfile();
			  if(uni.$vuex.state.globalData.currentConversId == conversationList[i].conversationID){
				  conversationList[i].unreadCount=0;
				  TencentIM.setMessageRead(conversationList[i].conversationID);
			  }
			  //显示红点
			  conversationList[i].redDot=false;
			  
			  // 免打扰不计入提示总消息数量
			  if(conversationList[i].messageRemindType == 'AcceptAndNotify'){
				  sum+=conversationList[i].unreadCount;
			  }
			  conversationList[i].lastMessage.lastTimeString=uni.$utils.formatTimestamp(conversationList[i].lastMessage.lastTime);
		      for(let j in makr){
				    //console.log(j);
				    unreadCount='';
					repString=conversationList[i].lastMessage.messageForShow;
					if(repString == ' ') repString=conversationList[i].lastMessage.payload.text;
					//console.log(repString);
					repString=repString.replace(makr[j].rule,makr[j].content);
					
					if(makr[j].content != ' '){
						repString=repString.split(uni.$appConfig.RED_NUMBER);
						if(repString[0].indexOf(makr[j].content) > -1) repString[0]=makr[j].content;
						conversationList[i].lastMessage.messageForShow=repString[0];
					}else{
						conversationList[i].lastMessage.messageForShow=repString;
					}
					// 免打扰不计入提示总消息数量
					if(conversationList[i].messageRemindType == 'AcceptAndNotify'){
						if(conversationList[i].unreadCount > 99){
							unreadCount='99+';
						}else if(conversationList[i].unreadCount > 0){
							unreadCount=conversationList[i].unreadCount;
						} 
					}else{
						if(conversationList[i].unreadCount > 0){
							conversationList[i].redDot=true;
						}
					}
					conversationList[i].unreadCountString=unreadCount;
			  }
			  emojiString=conversationList[i].lastMessage.messageForShow;
			  emojiString = TencentIM.replaceEmojiTags(emojiString);
			  if(conversationList[i].lastMessage.isRevoked) emojiString='[撤回消息]';
			  conversationList[i].lastMessage.messageForShow=emojiString;
			
		  }
		  uni.$vuex.state.globalData.tabBar.list[0].count=sum;
		  uni.$vuex.state.globalData.conversationList= conversationList;
		  uni.$vuex.state.globalData.isSyncCompleted=isSyncCompleted;
		  console.log('getConversationList',conversationList);
		 // console.log('getConversationList',uni.$vuex.state.globalData.isSyncCompleted);
		}).catch(function(imError) {
		  //console.warn('getConversationList error:', imError); // 获取会话列表失败的相关信息
		});
	},
	/**
	 * 文本消息发送 
	 *  type   类型:0单聊, 1群聊
	 *  toId   类型:单聊即用户ID,群聊即群ID
	 */
	createTextMessage:async(type,toId,msg,successBack,cloudCustomData='')=>{
		if(!TencentIM.instance().isReady){
			uni.$utils.showToast('[-100000]服器内部错误');
			return;
		}
		let TYPES=TencentCloudChat.TYPES.CONV_C2C; // 单聊
		if(type == 1) TYPES=TencentCloudChat.TYPES.CONV_GROUP;
		let message = TencentIM.instance().createTextMessage({
			to: toId.toString(),
			conversationType: TYPES,
			payload: {
			    text: msg
			},
			messageControlInfo:{
				excludedFromUnreadCount:false,
				excludedFromLastMessage:true,
			},
			// 支持C2C消息已读回执功能，如果您发消息需要已读回执，需购买旗舰版套餐，并且创建消息时将 needReadReceipt 设置为 true
			needReadReceipt: false,
			// 消息自定义数据（云端保存，会发送到对端，程序卸载重装后还能拉取到）
			cloudCustomData: cloudCustomData
		});
		
		// 2. 发送消息
		let promise = TencentIM.instance().sendMessage(message);
		promise.then(function(imResponse) {
		  // 发送成功
		  //console.log(imResponse);
		   typeof successBack == "function" && successBack(imResponse);
		}).catch(function(imError) {
			
		  // 发送失败
		  //console.warn('sendMessage error:', imError);
		  if(imError.code == 6014){ // 未登录
			  //TencentIM.login(type,toId,msg,successBack);
			  uni.$unsetToken();
			  uni.$utils.setCache('tencentimsig',null);
			  try{TencentIM.logout();}catch (err) {}
			  uni.$utils.goPage('/pages/login-app/login-app',2);
			  return;
		  }else if(imError.code == 6026){ // 自动登录时，并没有登录过该用户，这时候请调用 login 接口重新登录
			  //TencentIM.login(type,toId,msg,successBack);
			  uni.$unsetToken();
			  uni.$utils.setCache('tencentimsig',null);
			  try{TencentIM.logout();}catch (err) {}
			  uni.$utils.goPage('/pages/login-app/login-app',2);
			  return;
		  }else if(imError.code == 3003){ // 多实例登录被逼下线再次登录
			  //TencentIM.login(type,toId,msg,successBack);
			  uni.$unsetToken();
			  uni.$utils.setCache('tencentimsig',null);
			  try{TencentIM.logout();}catch (err) {}
			  uni.$utils.goPage('/pages/login-app/login-app',2);
			  return;
		  }else{
			  uni.$utils.showToast('['+imError.code+']'+imError.message);
		  }
		  
		});
	},
	
	//创建图片消息
	createImageMessage:(type,toId,fileObject,successBack)=>{
		if(!TencentIM.instance().isReady){
			uni.$utils.showToast('[-100000]服器内部错误');
			return;
		}
		let TYPES=TencentCloudChat.TYPES.CONV_C2C; // 单聊
		if(type == 1) TYPES=TencentCloudChat.TYPES.CONV_GROUP;
		let message=null;
		let promise=null;
		for(let i in fileObject.tempFiles){
			message = TencentIM.instance().createImageMessage({
				to: toId.toString(),
				conversationType: TYPES,
				
				payload: {
				   file: {tempFiles:[{path:fileObject.tempFiles[i].path}]}//fileObject
				},
			
				// 支持C2C消息已读回执功能，如果您发消息需要已读回执，需购买旗舰版套餐，并且创建消息时将 needReadReceipt 设置为 true
				needReadReceipt: false,
				// 消息自定义数据（云端保存，会发送到对端，程序卸载重装后还能拉取到）
				// cloudCustomData: 'your cloud custom data'
				/*onProgress: function(event) { 
					//console.log('file uploading:', event) 
				}*/
			});
			// 2. 发送消息
			promise = TencentIM.instance().sendMessage(message);
			promise.then(function(imResponse) {
			  // 发送成功
			  //console.log('createImageMessage'+imResponse);
			   typeof successBack == "function" && successBack(imResponse);
			}).catch(function(imError) {
			  // 发送失败
			  //console.warn('sendMessage error:', imError);
			  if(imError.code == 6014){ // 未登录
				  //TencentIM.login(type,toId,msg,successBack);
				  uni.$unsetToken();
				  uni.$utils.setCache('tencentimsig',null);
				  try{TencentIM.logout();}catch (err) {}
				  uni.$utils.goPage('/pages/login-app/login-app',2);
				  return;
			  }else if(imError.code == 6026){ // 自动登录时，并没有登录过该用户，这时候请调用 login 接口重新登录
				  //TencentIM.login(type,toId,fileObject,successBack);
				  uni.$unsetToken();
				  uni.$utils.setCache('tencentimsig',null);
				  try{TencentIM.logout();}catch (err) {}
				  uni.$utils.goPage('/pages/login-app/login-app',2);
				  return;
			  }else if(imError.code == 3003){ // 多实例登录被逼下线再次登录
				   uni.$unsetToken();
				   uni.$utils.setCache('tencentimsig',null);
				   try{TencentIM.logout();}catch (err) {}
				   uni.$utils.goPage('/pages/login-app/login-app',2);
				   return;
			  }else{
				  uni.$utils.showToast('['+imError.code+']'+imError.message);
			  }
			  
			});
		}
	},
	
	//创建视频消息
	createVideoMessage:(type,toId,fileObject,successBack)=>{
		if(!TencentIM.instance().isReady){
			uni.$utils.showToast('[-100000]服器内部错误');
			return;
		}
		
		let TYPES=TencentCloudChat.TYPES.CONV_C2C; // 单聊
		if(type == 1) TYPES=TencentCloudChat.TYPES.CONV_GROUP;
		let message = TencentIM.instance().createVideoMessage({
			to: toId.toString(),
			conversationType: TYPES,
			payload: {
			   file: fileObject
			},
		
			// 支持C2C消息已读回执功能，如果您发消息需要已读回执，需购买旗舰版套餐，并且创建消息时将 needReadReceipt 设置为 true
			needReadReceipt: false,
			// 消息自定义数据（云端保存，会发送到对端，程序卸载重装后还能拉取到）
			// cloudCustomData: 'your cloud custom data'
			/*onProgress: function(event) { 
				//console.log('file uploading:', event) 
			}*/
		});
		// 2. 发送消息
		let promise = TencentIM.instance().sendMessage(message);
		promise.then(function(imResponse) {
		  // 发送成功
		  //console.log('createImageMessage'+imResponse);
		   typeof successBack == "function" && successBack(imResponse);
		}).catch(function(imError) {
		  // 发送失败
		  //console.warn('sendMessage error:', imError);
		  if(imError.code == 6014){ // 未登录
			  //TencentIM.login(type,toId,msg,successBack);
			  uni.$unsetToken();
			  uni.$utils.setCache('tencentimsig',null);
			  try{TencentIM.logout();}catch (err) {}
			  uni.$utils.goPage('/pages/login-app/login-app',2);
			  return;
		  }else if(imError.code == 6026){ // 自动登录时，并没有登录过该用户，这时候请调用 login 接口重新登录
			  //TencentIM.login(type,toId,fileObject,successBack);
			  uni.$unsetToken();
			  uni.$utils.setCache('tencentimsig',null);
			  try{TencentIM.logout();}catch (err) {}
			  uni.$utils.goPage('/pages/login-app/login-app',2);
			  return;
		  }else if(imError.code == 3003){ // 多实例登录被逼下线再次登录
		   uni.$unsetToken();
		   uni.$utils.setCache('tencentimsig',null);
		   try{TencentIM.logout();}catch (err) {}
		   uni.$utils.goPage('/pages/login-app/login-app',2);
		   return;	  
		  }else{
			  uni.$utils.showToast('['+imError.code+']'+imError.message);
		  }
		  
		});
	},	
	
	//仓建语音消息
	createAudioMessage:(type,toId,successBack,loadBack=null)=>{
		let TYPES=TencentCloudChat.TYPES.CONV_C2C; // 单聊
		if(type == 1) TYPES=TencentCloudChat.TYPES.CONV_GROUP;
		const recorderManager = uni.getRecorderManager();
		// 录音部分参数
		const recordOptions = {
		  duration: 60000, // 录音的时长，单位 ms，最大值 600000（10 分钟）
		  sampleRate: 44100, // 采样率
		  numberOfChannels: 1, // 录音通道数
		  encodeBitRate: 192000, // 编码码率
		  format: 'aac' // 音频格式，选择此格式创建的音频消息，可以在即时通信 IM 全平台（Android、iOS、微信小程序和Web）互通
		};
		// 2.1 监听录音错误事件
		recorderManager.onError(function(errMsg) {
		  console.warn('recorder error:', errMsg);
		  uni.$utils.showToast(errMsg);
		});
		// 2.2 监听录音结束事件，录音结束后，调用 createAudioMessage 创建音频消息实例
		recorderManager.onStop(function(res) {
			  //console.log('recorder stop', res);
			  if(loadBack) loadBack();
			  // 4. 创建消息实例，接口返回的实例可以上屏
			  const message = TencentIM.instance().createAudioMessage({
				to: toId,
				conversationType:TYPES,
				// 消息优先级，用于群聊。如果某个群的消息超过了频率限制，后台会优先下发高优先级的消息，详细请参考：https://cloud.tencent.com/document/product/269/3663#.E6.B6.88.E6.81.AF.E4.BC.98.E5.85.88.E7.BA.A7.E4.B8.8E.E9.A2.91.E7.8E.87.E6.8E.A7.E5.88.B6)
				// 支持的枚举值：TencentCloudChat.TYPES.MSG_PRIORITY_HIGH, TencentCloudChat.TYPES.MSG_PRIORITY_NORMAL（默认）, TencentCloudChat.TYPES.MSG_PRIORITY_LOW, TencentCloudChat.TYPES.MSG_PRIORITY_LOWEST
				// priority: TencentCloudChat.TYPES.MSG_PRIORITY_NORMAL,
				payload: {
				  file: res
				},
				// 消息自定义数据（云端保存，会发送到对端，程序卸载重装后还能拉取到）
				// cloudCustomData: 'your cloud custom data'
				// 音频上传进度回调
				onProgress: function(event) { console.log('file uploading:', event) }
			});
			//console.log('message',message);
			// 5. 发送消息
			let promise = TencentIM.instance().sendMessage(message);
			promise.then(function(imResponse) {
				// 发送成功
				//console.log(imResponse);
				typeof successBack == "function" && successBack(imResponse);
			}).catch(function(imError) {
				  // 发送失败
				  console.warn('sendMessage error:', imError);
			});
		});
		// 3. 开始录音
		recorderManager.start(recordOptions);
		return recorderManager;
	},
	
	//拉取消息列表
	getMessageList:async (conversationID,nextReqMessageID)=>{
		let param={conversationID:conversationID};
		if(nextReqMessageID) param.nextReqMessageID=nextReqMessageID;
		let promise =await TencentIM.instance().getMessageList(param);
		if(promise.data.messageList.length > 0){ //清空本地会话未读数
			for(let i in promise.data.messageList){
				promise.data.messageList[i]=TencentIM.messageCustom(promise.data.messageList[i]);
				if((promise.data.messageList[i].cloudCustomData).indexOf('card') > -1){ // 私聊发送卡片
					promise.data.messageList[i].customCard=JSON.parse(promise.data.messageList[i].cloudCustomData);
				}
			}
		}
		console.log('getMessageList',promise.data.messageList);
		return promise.data;
	},
	
	// 处理消自定义
	messageCustom:(data)=>{
		let makr=uni.$appConfig.IM_PREFIX_MAKR;
		let repString='';
		let text='';
		repString=data.payload.text;
		
		if(repString){
			for(let j in makr){
				if(repString.indexOf(makr[j].rule) > -1){
					if(j == 'fa_hong_bao'){ // 发红包
						data.type='fa_hong_bao';
						text=data.payload.text;
						text=text.split(uni.$appConfig.RED_NUMBER);
						//console.log('uni.$appConfig.RED_NUMBER',uni.$appConfig.RED_NUMBER);
						data.payload.text=text[0];//显示标题
						repString=text[0];
						data.payload.number=text[1];//显示金额数量
						data.payload.id=text[2];//显示红包ID
					}else if(j == 'shou_hong_bao'){ // 收红包
						data.type='shou_hong_bao';
						text=data.payload.text;
						text=text.split(uni.$appConfig.RED_NUMBER);
						data.payload.text=text[0];//显示标题
						repString=text[0];
						data.payload.number=text[1];//显示金额数量
						data.payload.id=text[2];//显示红包ID
					}else if(j == 'fa_tu_pian'){ // 自定义发的图片或发出收藏的图片[纯URL]
						data.type='fa_tu_pian';
					}else if(j == 'fa_shi_pin'){ // 自定义发的视频或发出收藏的视频[纯URL]
						data.type='TIMVideoFileElem';
						let makrTemp=uni.$appConfig['VIDEO_COLLECT_MAKR'];
						let content=(data.payload.text).toString();
						content=content.replace(makr[j].rule,'');
						let test=content.split(makrTemp);
						let videoUrl=test[0];
						let thumb=test[1];
						let thumbW=test[2];
						let thumbH=test[3];
						let time=test[4];
						data.payload.videoUrl=videoUrl;
						data.payload.thumbUrl=thumb;
						data.payload.thumbWidth=thumbW;
						data.payload.thumbHeight=thumbH;
						data.payload.videoSecond=time;
					}else if(j == 'jia_ru_qun_liao'){
						data.type='jia_ru_qun_liao';
					}
				}
			    repString=repString.replace(makr[j].rule,'');
			}
		}
		if(data.type == 'TIMVideoFileElem'){
			data.payload.videoSecond_str=uni.$utils.formatSeconds(data.payload.videoSecond);
		}
		data.payload.text=repString;
		data.timeString = uni.$utils.formatTimestamp(data.time);
		return data;
	},
	
	//删除消息
	deleteMessage:(arrays,callBack)=>{
		let promise  = TencentIM.instance().deleteMessage(arrays);
		promise.then(function(imResponse) {
		  typeof successBack == "function" && successBack(imResponse);
		}).catch(function(imError) {
		  // 删除消息失败
		  console.warn('deleteMessage error:', imError);
		  uni.$utils.showToast('删除失败');
		});
	},
	
	/**
	 * (置顶/取消置顶)会话消息
	 * conversationID  会话ID
	 * type    true置顶,false取消置顶
	 */
	pinConversation:(conversationID,type)=>{
		let promise = TencentIM.instance().pinConversation({ conversationID: conversationID, isPinned: type });
		promise.then(function(imResponse) {
		  // 置顶会话成功
		  //const { conversationID } = imResponse.data; // 被置顶的会话 ID
		  TencentIM.getConversationList();
		}).catch(function(imError) {
		  //console.warn('pinConversation error:', imError); // 置顶会话失败的相关信息
		  uni.$utils.showToast(imError);
		});
	},
	
	//删除会话
	deleteConversation:(conversationID)=>{
		let promise = TencentIM.instance().deleteConversation(conversationID);
		promise.then(function(imResponse) {
		  // 删除会话成功
		  //const { conversationID } = imResponse.data; // 被删除的会话 ID
		}).catch(function(imError) {
		  //console.warn('deleteConversation error:', imError); // 删除会话失败的相关信息
		  uni.$utils.showToast(imError);
		});
	},
	
	//主动撤回消息
	revokeMessage:(message,callBack)=>{
		// 主动撤回消息
		let promise = TencentIM.instance().revokeMessage(message);
		promise.then(function(imResponse) {
		  typeof successBack == "function" && successBack(imResponse);
		}).catch(function(imError) {
		    // 消息撤回失败
		   console.warn('revokeMessage error:', imError);
		   uni.$utils.showToast('消息撤回已超时');
		});
	},
	
	//清空本地某个会话未读数
	setMessageRead:(conversationID)=>{
		TencentIM.instance().setMessageRead({ conversationID });
	},

	/**
	 * C2C 消息免打扰
	 * userIDList  用户ID数组
	 * type        类型：0消息免打扰，1取消免打扰
	 * allBack     成功回调
	 */
	setUsersRemindType:(userIDList,type,allBack)=>{
		for(let i = 0; i < userIDList.length;i++) userIDList[i]=userIDList[i].toString();
		type=type == 0 ? TencentCloudChat.TYPES.MSG_REMIND_ACPT_NOT_NOTE : TencentCloudChat.TYPES.MSG_REMIND_ACPT_AND_NOTE;
		let promise = TencentIM.instance().setMessageRemindType({ userIDList: userIDList, messageRemindType: type });
		promise.then(function(imResponse) {
		  // 设置成功后 SDK 会触发 TencentCloudChat.EVENT.CONVERSATION_LIST_UPDATED 事件（遍历列表，并读取 Conversation.messageRemindType）
		  /*const { successUserIDList, failureUserIDList } = imResponse.data;
		  // 删除成功的 userIDList
		  successUserIDList.forEach((item) => {
		    const { userID } = item;
		  });
		  // 删除失败的 userIDList
		  failureUserIDList.forEach((item) => {
		    const { userID, code, message } = item;
		  });*/
		  allBack(imResponse);
		}).catch(function(imError) {
		  //console.log('setMessageRemindType error:', imError);
		  uni.$utils.showToast(imError);
		});
	},

	/**
	 * 群消息免打扰
	 * userIDList  群组ID
	 * type        类型：0消息免打扰，1取消免打扰
	 * allBack     成功回调 
	 */
	setGroupRemindType:(groupID,type,allBack)=>{
		//console.log('type',type);   
		type=type == 0 ? TencentCloudChat.TYPES.MSG_REMIND_ACPT_NOT_NOTE : TencentCloudChat.TYPES.MSG_REMIND_ACPT_AND_NOTE;
		let promise = TencentIM.instance().setMessageRemindType({ groupID: groupID, messageRemindType: type });
		promise.then(function(imResponse) {
		  // 设置消息免打扰成功
		  allBack(imResponse);
		}).catch(function(imError) {
		  // 设置消息免打扰失败
		  //console.log('setMessageRemindType error:', imError);
		  uni.$utils.showToast(imError);
		});
	},
    // 替换表情
	replaceEmojiTags:(message)=>{
		// 正则解释：匹配 [TUIEmoji_任意字符] 格式的字符串
		const emojiRegex = /\[TUIEmoji_[^\]]+\]/g;
		// 替换所有匹配项为 [表情]
		return message.replace(emojiRegex, '[表情]');
	},
	//通知消息过滤
	noticeFilter:(type,repString)=>{
		let str='';
		if(type == 'TIMTextElem'){ // 文本消息
			let makr=uni.$appConfig.IM_PREFIX_MAKR;
			let isreplace=false;
			for(let j in makr){
				if(repString.indexOf(makr[j].rule) > -1){
					if(makr[j] == 'fa_hong_bao'){ // 发红包
						str='[红包]';
					}else if(makr[j] == 'shou_hong_bao'){ // 收红包
						str='[收红包]';
					}else if(makr[j] == 'fa_tu_pian'){ // 自定义发的图片或发出收藏的图片[纯URL]
						str='[图片]';
					}else if(makr[j] == 'fa_shi_pin'){ // 自定义发的视频或发出收藏的视频[纯URL]
						str='[视频]';
					}
					isreplace=true;
				}
			}
			if(repString.length > 22) str=repString.substring(0,12)+'...';
			else str= repString;
		}else if(type == 'TIMImageElem'){ // 图片
			str='[图片]';
		}else if(type == 'TIMVideoFileElem'){ // 视频
			str='[视频]';
		}else if(type == 'TIMSoundElem'){ // 语音
			str='[语音]';
		}
		return str;
	},
	//申请加入群聊
	joinGroup:async (groupID)=>{
		let imResponse =await TencentIM.instance().joinGroup({ groupID: groupID ,silent: true});
		if(!imResponse.data) return -1;
		switch (imResponse.data.status) {
		    case TencentCloudChat.TYPES.JOIN_STATUS_WAIT_APPROVAL: // 等待管理员同意
			  return 0;
		    case TencentCloudChat.TYPES.JOIN_STATUS_SUCCESS: // 加群成功
			  return 1;
		      //console.log(imResponse.data.group); // 加入的群组资料
		    case TencentCloudChat.TYPES.JOIN_STATUS_ALREADY_IN_GROUP: // 已经在群中
			  return 2;
		}
	},
	//直接加入群聊
	addGroupMember:(groupID,userIDLis,successBack)=>{
		let promise = TencentIM.instance().addGroupMember({groupID: groupID, userIDList: userIDLis,silent: true});
		promise.then(function(imResponse) {
		  //console.log(imResponse.data.successUserIDList); // 添加成功的群成员 userIDList
		  //console.log(imResponse.data.failureUserIDList); // 添加失败的群成员 userIDList
		  //console.log(imResponse.data.existedUserIDList); // 已在群中的群成员 userIDList
		  // 一个用户 userX 最多允许加入 N 个群，如果已经加入了 N 个群，此时再尝试添加 userX 为群成员，则 userX 不能正常加群
		  // SDK 将 userX 的信息放入 overLimitUserIDList，供接入侧处理
		  //console.log(imResponse.data.overLimitUserIDList); // 超过了“单个用户可加入群组数”限制的用户列表
		  //console.log(imResponse.data.group); // 添加后的群组信息
		  successBack(imResponse.data);
		}).catch(function(imError) {
		  //console.warn('addGroupMember error:', imError); // 错误信息
		  uni.$utils.showToast(imError);
		});
	},
	//拉取群成员
	getGroupMemberProfile:async(groupID,userIDList)=>{
		try {
		let promise=await TencentIM.instance().getGroupMemberProfile({
             groupID: groupID,
             userIDList: userIDList, // 请注意：即使只拉取一个群成员的资料，也需要用数组类型，例如：userIDList: ['user1']
             //memberCustomFieldFilter: ['group_member_custom'], // 筛选群成员自定义字段：group_member_custom
        });
		//console.log('promise',promise);
		return promise.data.memberList;
		}catch (error) {
           //console.error('获取群组列表失败', error);
           //throw error;
		   return [];
        }
	},
	//获取群资料
	getGroupProfile:async (groupID)=>{
		
		let promise =await TencentIM.instance().getGroupProfile({ groupID: groupID});
		console.log('promise',promise);
		/*promise.then(function(imResponse) {
		  console.log(imResponse.data.group);
		}).catch(function(imError) {
		  console.warn('getGroupProfile error:', imError); // 获取群详细资料失败的相关信息
		});*/
	},
	//群某成员禁言
	setGroupMemberMuteTime:async(groupID,userId,time,allBack)=>{
		
		let promise = TencentIM.instance().setGroupMemberMuteTime({
		  groupID: groupID,
		  userID: userId.toString(),
		  muteTime: time // 禁言10分钟；设为0，则表示取消禁言
		});
		promise.then(function(imResponse) {
		  //console.log(imResponse.data.group); // 修改后的群资料
		  //console.log(imResponse.data.member); // 修改后的群成员资料
		  allBack(imResponse.data.group,imResponse.data.member);
		}).catch(function(imError) {
		  //console.warn('setGroupMemberMuteTime error:', imError); // 禁言失败的相关信息
		  uni.$utils.showToast(imError);
		});
	},
	//拉黑对方
	addToBlacklist:(userIDList,allBack)=>{
		let promise = TencentIM.instance().addToBlacklist({userIDList: userIDList}); // 请注意：即使只添加一个用户账号到黑名单，也需要用数组类型，例如：userIDList: ['user1']
		promise.then(function(imResponse) {
		  console.log(imResponse.data); // 被拉黑的全量账号列表，结构为包含用户 userID 的数组 - [userID]
		  allBack(imResponse.data);
		}).catch(function(imError) {
		  //console.warn('addToBlacklist error:', imError); // 添加用户到黑名单列表失败的相关信息
		  uni.$utils.showToast(imError);
		});
	},
	//解除拉黑对方
	removeFromBlacklist:async(userIDList)=>{
		try{
			let promise =await TencentIM.instance().removeFromBlacklist({userIDList: userIDList});
			return promise;
		}catch(imError){
			return imError;
		}
	},
	//获取我的黑名单列表
	getBlacklist:async()=>{
		try{
			let promise =await TencentIM.instance().getBlacklist();
			return promise;
		}catch(imError){
			return imError;
		}
	},
	//解散群
	dismissGroup:async(groupID)=>{
		try{
			let promise =await TencentIM.instance().dismissGroup(groupID);
			return promise;
		}catch(imError){
			return imError;
		}
	},
	//退出群聊
	quitGroup:async(groupID)=>{
		try{
			let promise =await TencentIM.instance().quitGroup(groupID);
			//console.log(promise.data.groupID); // 退出成功的群 ID
			return promise;
		}catch(imError){
			return imError;
		}
	},
	//移出群聊
	deleteGroupMember:(groupID,userIDList,reason,successBack,fialBack)=>{
		// 非直播群（AVChatRoom）删除群成员
		let promise = TencentIM.instance().deleteGroupMember({groupID: groupID, userIDList:userIDList, reason: reason});
		promise.then(function(imResponse) {
		  //console.log(imResponse.data.group); // 删除后的群组信息
		  //console.log(imResponse.data.userIDList); // 被删除的群成员的 userID 列表
		  successBack(imResponse.data.group,imResponse.data.userIDList);
		}).catch(function(imError) {
		  //console.warn('deleteGroupMember error:', imError); // 错误信息
		  fialBack(imError);
		});
	},
	//获取加群申请和邀请进群申请列表数量
	getGroupApplicationListCount:()=>{
		let promise = TencentIM.instance().getGroupApplicationList();
		promise.then(function(imResponse) {
			if(imResponse.data){
				if(imResponse.data.applicationList){
					let count=imResponse.data.applicationList.length;
					if(count > 99) count = '99+';
					uni.$vuex.state.globalData.tabBar.list[3].count=count;
					uni.$vuex.state.globalData.groupApplicationCount=count;
				}
			}
		});
	},
	//获取加群申请和邀请进群申请列表
	getGroupApplicationList:async()=>{
		let promise = await TencentIM.instance().getGroupApplicationList();
		let data=promise.data || {};
		if(!data.applicationList) return [];
		let tempList=uni.$utils.twoObj(data.applicationList,100);
		
		for(let i in tempList){
			let userIDs=[];
			let t=0;
			for(let j in tempList[i]){
				userIDs[t]=(tempList[i][j].applicant).toString();
				t++;
			}
			let user=await TencentIM.getUserProfile(userIDs);
			for(let k in tempList[i]){
				for(let p in user){
					if(user[p].userID == tempList[i][k].applicant){
						tempList[i][k]['avatar']=user[p].avatar;
						tempList[i][k]['gender']=user[p].gender;
						break;
					}
				}
			}
		}
		let list=[];
		let i2=0;
		for(let i in tempList) {
			for(let j in tempList[i]){
				list[i2++]=tempList[i][j];
			}
		}
		return list;
	},
	
	/**
	 * 同意或拒绝入群申请
	 * handleAction 处理结果 Agree(同意) / Reject(拒绝)
	 * handleMessage  附言
	 * application    加群申请者对像
    */
	handleGroupApplication:(handleAction,handleMessage,application,callBack)=>{
		//console.log(application);return;
		// 通过系统通知处理加群申请
		let promise = TencentIM.instance().handleGroupApplication({
		  handleAction: handleAction,
		  handleMessage: handleMessage,
		  //message: message, // 申请加群群系统通知的消息实例
		  application:{...application}
		});
		//console.log(message);return;
		promise.then(function(imResponse) {
		  //console.log(imResponse.data.group); // 群组资料
		  callBack(imResponse.data.group);
		  TencentIM.createTextMessage(1,application.groupID,'欢迎“'+application.applicantNick+'”加入群聊！',()=>{});
		}).catch(function(imError){
		  //console.warn('handleGroupApplication error:', imError); // 错误信息
		  uni.$utils.showToast(imError);
		});
	},
	
	//获取用户资料
	getUserProfile:async(userIDList)=>{
		let promise =await TencentIM.instance().getUserProfile({
		  userIDList: userIDList // 请注意：即使只拉取一个用户的资料，也需要用数组类型，例如：userIDList: ['user1']
		});
		return promise.data;
		//console.log('getUserProfile',promise.data);
	},
	
	netStateChange:(event)=>{
		if(event.data.state == TencentCloudChat.TYPES.NET_STATE_CONNECTED){ // 网络已连接
			uni.$vuex.state.globalData.netStateChange=1;
		}else if(event.data.state == TencentCloudChat.TYPES.NET_STATE_CONNECTING){ // 网络连接中[前网络不稳定”或“连接中”]
			uni.$vuex.state.globalData.netStateChange=0;
		}else if(event.data.state == TencentCloudChat.TYPES.NET_STATE_DISCONNECTED){// 未接入网络。接入侧可根据此状态提示“当前网络不可用”。SDK 仍会继续重试，若用户网络恢复，SDK 会自动同步消息
			uni.$vuex.state.globalData.netStateChange=2;
		}
	},

	//临听退出具名函数
	kickedOut:(event)=>{
		console.log('kickedOut',event.data.type);
		// 收到被踢下线通知
		// event.name - TencentCloudChat.EVENT.KICKED_OUT
		// event.data.type - 被踢下线的原因，例如 :
		//   - TencentCloudChat.TYPES.KICKED_OUT_MULT_ACCOUNT 多实例登录被踢
		//   - TencentCloudChat.TYPES.KICKED_OUT_MULT_DEVICE 多终端登录被踢
		//   - TencentCloudChat.TYPES.KICKED_OUT_USERSIG_EXPIRED 签名过期被踢
		//   - TencentCloudChat.TYPES.KICKED_OUT_REST_API(REST API kick 接口踢出。)
		if(event.data.type == TencentCloudChat.TYPES.KICKED_OUT_MULT_ACCOUNT){ // 多实例登录被踢
		    uni.$utils.setCache('tencentimsig',null);
			uni.$unsetToken();
			TencentIM.logout();
			uni.$utils.showModal('帐号已在另一台设备登录',0,()=>{
				uni.$utils.goPage('/pages/login-app/login-app',2);
			});
		}else if(event.data.type == TencentCloudChat.TYPES.KICKED_OUT_MULT_DEVICE){ // 多终端登录被踢
			uni.$utils.setCache('tencentimsig',null);
			uni.$unsetToken();
			TencentIM.logout();
			uni.$utils.showModal('帐号已在另一台设备登录',0,()=>{
				uni.$utils.goPage('/pages/login-app/login-app',2);
			});
		}else if(event.data.type == TencentCloudChat.TYPES.KICKED_OUT_USERSIG_EXPIRED){ // 签名过期被踢
		    uni.$utils.setCache('tencentimsig',null);
			TencentIM.logout();
			TencentIM.listen();
			TencentIM.login();
		}else if(event.data.type == TencentCloudChat.TYPES.KICKED_OUT_REST_API){ // REST API kick 接口踢出,检测到用户账号异常（如盗号），立即踢出所有在线设备。
			uni.$utils.setCache('tencentimsig',null);
			uni.$unsetToken();
			TencentIM.logout();
			uni.$utils.showModal('检测到用户账号异常',0,()=>{
				uni.$utils.goPage('/pages/login-app/login-app',2);
			});
		}
	},
	//退出登录
	logout:()=>{
		TencentIM.instance().off(TencentCloudChat.EVENT.NET_STATE_CHANGE,TencentIM.netStateChange);
		TencentIM.instance().off(TencentCloudChat.EVENT.SDK_NOT_READY,TencentIM.onSdkNotReady);
		TencentIM.instance().off(TencentCloudChat.EVENT.SDK_READY,TencentIM.noSdkIsReady);
		TencentIM.instance().off(TencentCloudChat.EVENT.MESSAGE_RECEIVED,TencentIM.messageReceived);
		TencentIM.instance().off(TencentCloudChat.EVENT.CONVERSATION_LIST_UPDATED,TencentIM.conversation);
		TencentIM.instance().off(TencentCloudChat.EVENT.KICKED_OUT,TencentIM.kickedOut);
		let promise = TencentIM.instance().logout();
		promise.then(function(imResponse) {
		  console.log(imResponse.data); // 登出成功
		}).catch(function(imError) {
		  console.log('logout error:', imError);
		});
		TencentIM.object.destroy();
		TencentIM.object=null;
		TencentIM.isListening=null;
	},
	//统一监听事件
	listen:()=>{
		if(TencentIM.isListening) return;
		//TencentIM.netStateChange();
		TencentIM.instance().on(TencentCloudChat.EVENT.NET_STATE_CHANGE,TencentIM.netStateChange);
		
		//TencentIM.onSdkNotReady();	
		TencentIM.instance().on(TencentCloudChat.EVENT.SDK_NOT_READY,TencentIM.onSdkNotReady);
		
		//TencentIM.noSdkIsReady();
		TencentIM.instance().on(TencentCloudChat.EVENT.SDK_READY,TencentIM.noSdkIsReady);
		
		//TencentIM.messageReceived();
		TencentIM.instance().on(TencentCloudChat.EVENT.MESSAGE_RECEIVED,TencentIM.messageReceived);
		
		//TencentIM.conversation();
		TencentIM.instance().on(TencentCloudChat.EVENT.CONVERSATION_LIST_UPDATED,TencentIM.conversation);
		
		//TencentIM.kickedOut();
		TencentIM.instance().on(TencentCloudChat.EVENT.KICKED_OUT, TencentIM.kickedOut); 
		TencentIM.isListening=true;
		//console.log('IM listen');
	},

};
uni.TIM=TencentIM;